package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {
   @Autowired
   private JedisPool jedisPool;
   @Reference
   private OrderService orderService;

   /**
    * 体检预约:校验验证码,预约成功发送短信给客户
    * @param map
    * @return 数据中只包含预约id
    */
   @RequestMapping("/submit")
   public Result submit(@RequestBody Map map) {
      //1.获取验证码
      String validateCode = (String) map.get("validateCode");//用户输入的验证码
      String telephone = (String) map.get("telephone");
      String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);//redis获取对应验证码
      //2.校验,失败直接返回结果
      if (validateCode == null ||codeInRedis == null || !codeInRedis.equals(validateCode)) {
         return new Result(false, MessageConstant.VALIDATECODE_ERROR);
      }
      //3.校验成功,调用服务,进行预约处理,并获取结果Result
      Result result = null;
      try {
         map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约方式
         result = orderService.order(map);
      } catch (Exception e) {
         e.printStackTrace();
         //4.预约失败,返回结果
         return result;
      }

      //5.预约成功,发送通知短信
      String orderDate = (String) map.get("orderDate");
      try {
         SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
      } catch (ClientException e) {
         e.printStackTrace();
      }

      return result;
   }

   /**
    * 通过预约id获取相应数据
    * @param orderId
    * @return 获取member体检人,setmeal体检套餐名,orderDate体检日期,orderType预约类型
    */
   @RequestMapping("/findById/{orderId}")
   public Result findById(@PathVariable Integer orderId) {
      //调用服务,获取map集合封装对应数据
      try {
         Map map = orderService.findByOrderId(orderId);
         return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
      } catch (Exception e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
      }

   }

}
